package com.erp.auto.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.erp.auto.domain.ErpAutoPulishProductProject;
import com.erp.auto.domain.dto.RestartProjectDto;
import com.ruoyi.ae.api.RemoteAeCategoryService;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.ae.api.RemoteAeStoreInfoService;
import com.ruoyi.auto.api.domain.ErpAutoSellerStoreConfig;
import com.erp.auto.domain.ErpAutoSellerStoreConfigErrorCategory;
import com.erp.auto.domain.bo.ErpAutoPublishProductProjectBo;
import com.erp.auto.mapper.ErpAutoPulishProductProjectMapper;
import com.erp.auto.mapper.ErpAutoPulishProductProjectTaskMapper;
import com.erp.auto.mapper.ErpAutoSellerStoreConfigErrorCategoryMapper;
import com.erp.auto.mapper.ErpAutoSellerStoreConfigMapper;
import com.erp.auto.service.IErpAutoPublishProductProjectService;
import com.ruoyi.ae.api.RemoteAeActivityService;
import com.ruoyi.auto.api.domain.ErpAutoPulishProductProjectTask;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.HttpSendUtils;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.gather.api.RemotePublishProductService;
import com.ruoyi.gather.api.RemoteSellerProductService;
import com.ruoyi.gather.api.RemoteSellerStoreProductService;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.gather.api.domain.dto.AutoQueryInfoDto;
import com.ruoyi.gather.api.domain.dto.AutoQueryPriceTemplateInfoDto;
import com.ruoyi.gather.api.domain.dto.PublishInnerAuthDto;
import com.ruoyi.shop.api.RemoteSellerStoreActivityService;
import com.ruoyi.shop.api.RemoteSellerStoreFreightTemplateService;
import com.ruoyi.shop.api.RemoteSellerStorePriceTemplateService;
import com.ruoyi.shop.api.domain.ErpSellerStorePriceTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import static jodd.util.ThreadUtil.sleep;

@RequiredArgsConstructor
@Service
public class ErpAutoPublishProductProjectServiceImpl implements IErpAutoPublishProductProjectService {
    @Resource
    RemoteAeProductService remoteAeProductService;
    @Resource
    RemoteAeActivityService remoteAeActivityService;
    @Resource
    RemoteSellerStorePriceTemplateService remoteSellerStorePriceTemplateService;
    @Resource
    RemoteSellerStoreFreightTemplateService remoteSellerStoreFreightTemplateService;
    @Resource
    RemotePublishProductService remotePublishProductService;
    @Resource
    RemoteSellerProductService remoteSellerProductService;
    @Resource
    RemoteSellerStoreProductService remoteSellerStoreProductService;
    @Resource
    RemoteSellerStoreActivityService remoteSellerStoreActivityService;

    private final ErpAutoPulishProductProjectMapper baseMapper;
    private final ErpAutoPulishProductProjectTaskMapper erpAutoPulishProductProjectTaskMapper;
    private final ErpAutoSellerStoreConfigErrorCategoryMapper erpAutoSellerStoreConfigErrorCategoryMapper;
    private final ErpAutoSellerStoreConfigMapper erpAutoSellerStoreConfigMapper;

    private static String ACCESS_TOKEN_KEY = "access_token_key:";

    /**
     * 刊登到在线商品库
     *
     * @param project
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Object> publishSellerStoreProduct(ErpAutoPulishProductProject project) {
        //查询个人商品库信息
        ErpSellerProduct sellerProductSel = new ErpSellerProduct();
        sellerProductSel.setSellerId(project.getUserId());
        sellerProductSel.setCollectProductId(project.getProductId());
        R<Object> sellerProductObject = remoteSellerProductService.getSellerProductInfo(sellerProductSel);
        String sellerProductString = JSONObject.toJSONString(sellerProductObject.getData());
        ErpSellerProduct sellerProduct = JSONObject.parseObject(sellerProductString, ErpSellerProduct.class);

        Long sellerProductId = sellerProduct.getId();


        Long taskId = project.getTaskId();
        //店铺id
        Long storeId = project.getStoreId();
        //查看该任务是否上架过商品
        //查询个人商品库延伸表信息


        ErpSellerStoreProductExpand sellerStoreProductExpandSel = new ErpSellerStoreProductExpand();
        sellerStoreProductExpandSel.setAutoTaskId(taskId);
        R<Object> sellerStoreProductExpandObject = remoteSellerStoreProductService.getErpSellerStoreProductExpandInfo(sellerStoreProductExpandSel);
        String sellerStoreProductExpandString = JSONObject.toJSONString(sellerStoreProductExpandObject.getData());
        ErpSellerStoreProductExpand sellerStoreProductExpand = JSONObject.parseObject(sellerStoreProductExpandString, ErpSellerStoreProductExpand.class);
        if (ObjectUtils.isNotNull(sellerStoreProductExpand)) {
            //删除在线商品库信息 重新上传
            Long sellerStoreProductId = sellerStoreProductExpand.getSellerStoreProductId();
            //查询在线商品库信息
            ErpSellerStoreProduct erpSellerStoreProductSel = new ErpSellerStoreProduct();
            erpSellerStoreProductSel.setId(sellerStoreProductId);
            R<Object> erpSellerStoreProductObject = remoteSellerStoreProductService.getSellerStoreProductInfo(erpSellerStoreProductSel);
            String sellerStoreProductString = JSONObject.toJSONString(erpSellerStoreProductObject.getData());
            ErpSellerStoreProduct sellerStoreProduct = JSONObject.parseObject(sellerStoreProductString, ErpSellerStoreProduct.class);
            if (ObjectUtils.isNotNull(sellerProduct)) {
                //删除在线商品库信息
                remoteSellerStoreProductService.deleteErpSellerStoreProduct(sellerStoreProduct);
                //删除在线商品库延伸表信息
                remoteSellerStoreProductService.deleteErpSellerStoreProductExpand(sellerStoreProductExpand);
                ErpSellerStoreProductSku erpSellerStoreProductSku = new ErpSellerStoreProductSku();
                erpSellerStoreProductSku.setSellerStoreProductId(sellerStoreProductId);
                R<Object> erpSellerStoreProductSkuListObject = remoteSellerStoreProductService.getSellerStoreProductSkuListInfo(erpSellerStoreProductSku);
                if (erpSellerStoreProductSkuListObject.getCode() == 200) {
                    String erpSellerStoreProductSkuListString = JSONObject.toJSONString(erpSellerStoreProductSkuListObject.getData());
                    List<ErpSellerStoreProductSku> erpSellerStoreProductSkuList = JSONArray.parseArray(erpSellerStoreProductSkuListString, ErpSellerStoreProductSku.class);
                    //删除sku表
                    remoteSellerStoreProductService.deletErpSellerStoreProductSkuList(erpSellerStoreProductSkuList);
                }
            }

        }

        //从个人库上传到在线库
        ErpSellerStoreProductExpand sellerStoreProductExpandNew = new ErpSellerStoreProductExpand();
        sellerStoreProductExpandNew.setPromiseTemplateId(0L);
        //活动 id
        //查找店铺活动信息 TODO 3.18

//        ErpSellerStorePromotionActivity activitySel = new ErpSellerStorePromotionActivity();
//        activitySel.setPromotionId(project.getProductDiscountId().toString());
//        R<Object> activityObject = remoteSellerStoreService.getPromotionActivityInfo(activitySel);
//        String sellerStoreProductString = JSONObject.toJSONString(activityObject.getData());
//        ErpSellerStorePromotionActivity activity = JSONObject.parseObject(sellerStoreProductString, ErpSellerStorePromotionActivity.class);
//
////        ErpSellerStorePromotionActivity activity = erpSellerStorePromotionActivityMapper.selectOne(
////                new LambdaQueryWrapper<ErpSellerStorePromotionActivity>().eq(ErpSellerStorePromotionActivity::getPromotionId, project.getProductDiscountId())
////        );
//        if (Objects.isNull(activity)) {
//            return R.fail("活动不存在");
//        }
        sellerStoreProductExpandNew.setActivityId(project.getActivityId());
        sellerStoreProductExpandNew.setPriceAdjustmentMethod("1");
        sellerStoreProductExpandNew.setReadjustPricesType(1);
        //智能定价模版id
        sellerStoreProductExpandNew.setTemplateId(project.getTemplateId());
        //品牌id
//        ErpSellerProduct sellerProduct = erpSellerProductMapper.selectById(sellerProductId);
        //TODO 改为内部类调用
//        JSONObject object = new JSONObject();
//        object.put("sellerProductId", sellerProductId.toString());
//        object.put("categoryId", sellerProduct.getCategoryId());
//        object.put("storeId", storeId);
        // TODO 3.18
//        R<Object> objectR = remoteSellerStoreService.queryStoreBrandInnerAuth(sellerProductId,sellerProduct.getCategoryId(),storeId);
//        System.out.println(objectR);
//        if (objectR.getCode() == 200) {
//            String brandId = (String) objectR.getData();
//            sellerStoreProductExpandNew.setBrandId(brandId.toString());
//        } else {
//            return R.fail(sellerProduct.getCategoryId(), objectR.getMsg());
//        }
        //默认自动匹配
        sellerStoreProductExpandNew.setIsAutoMate(1);
        //审核中处理方式
        sellerStoreProductExpandNew.setIsAudit(project.getReviewStatus());
        //库存扣减策略
        sellerStoreProductExpandNew.setReduceStrategy("payment_success_deduct");
        //添加任务id
        sellerStoreProductExpandNew.setAutoTaskId(project.getTaskId());
        //默认主图调序
        sellerStoreProductExpandNew.setIsMainImageReordering(1);
        //默认加水印
        sellerStoreProductExpandNew.setIsAddWatemark(1);
        //内部调用刊登方法

        PublishInnerAuthDto dto = new PublishInnerAuthDto();
        dto.setSellerProductId(sellerProductId);
        dto.setStoreId(storeId);
        dto.setStock(199L);
        dto.setErpSellerStoreProductExpand(sellerStoreProductExpandNew);
        R<Object> publishObj = remoteSellerStoreProductService.publishInnerAuth(dto);

        //判断是否成功
        if (publishObj.getCode() != 200) {
            return R.fail(publishObj.getData());
        } else {
            return R.ok("发布成功");
        }
    }


//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public R<Object> publishSellerProduct(ErpAutoPulishProductProject project) {
//
//        /** TODO start 上架前的验证店铺是否存在，商品是否合规 **/
////        R<Object> objectR = remoteSellerStoreService.getSellerStoreInfoById(project.getStoreId());
////        String toJSONString = JSONObject.toJSONString(objectR.getData());
////        ErpSellerStoreEmpower store = JSONObject.parseObject(toJSONString, ErpSellerStoreEmpower.class);
////        if (Objects.isNull(store)) {
////            return R.fail("店铺不存在");
////        }
////        //用户id
////        Long userId = project.getUserId();
////        //用户角色
//////        List<String> rolesList = sysRoleMapper.queryThisUserRole(userId.toString());
////        //将列表转为string
//////        String roles = String.join(",", rolesList);
////        //自动任务id
////        Long taskId = project.getTaskId();
////
////        //目标id
////        String productId = project.getProductId().toString();
////        //确认是否已经被全网下架
////        ErpProductUnifiedTakedown erpProductUnifiedTakedown = new ErpProductUnifiedTakedown();
////        erpProductUnifiedTakedown.setCollectProductId(Long.valueOf(productId));
////        erpProductUnifiedTakedown.setIsEffective(1);
////        erpProductUnifiedTakedown.setIsExecute(1);
////        R<Object> takedownListObject = remoteCollectProductService.getProductUnifiedTakedownListInfo(erpProductUnifiedTakedown);
////        String takedownListJSONString = JSONObject.toJSONString(takedownListObject.getData());
////        List<ErpProductUnifiedTakedown> takedownList = JSONArray.parseArray(takedownListJSONString, ErpProductUnifiedTakedown.class);
////
////        if (takedownList.size() > 0) {
////            return R.fail("该商品已被全网下架");
////        }
//        /** end 上架前的验证店铺是否存在，商品是否合规 **/
//
//        //个人商品库id
//        Long sellerProductId = null;
//        //判断是否已经上过个人商品库
//        ErpSellerProduct erpSellerProductSel = new ErpSellerProduct();
//        erpSellerProductSel.setSellerId(userId);
//        erpSellerProductSel.setCollectProductId(Long.valueOf(productId));
//        R<Object> sellerProductObject = remoteSellerProductService.getSellerProductInfo(erpSellerProductSel);
//        String sellerProductJSONString = JSONObject.toJSONString(sellerProductObject.getData());
//        ErpSellerProduct erpSellerProduct = JSONObject.parseObject(sellerProductJSONString, ErpSellerProduct.class);
//
//
//        if (Objects.isNull(erpSellerProduct)) {
////            //公共库
////            //将公共库商品刊登到个人库
////            R<Object> collectProductObject = remoteCollectProductService.getCollectProductInfoById(Long.valueOf(productId));
////            System.out.println(collectProductObject);
////            String collectProductJSONString = JSONObject.toJSONString(collectProductObject.getData());
////            ErpCollectProduct collectProduct = JSONObject.parseObject(collectProductJSONString, ErpCollectProduct.class);
////            if (collectProduct.getDelFlag().equals("2")) {
////                return R.fail("商品已被删除");
////            }
////
////            ErpCollectProductExpand collectProductExpandSel = new ErpCollectProductExpand();
////            collectProductExpandSel.setCollectProductId(Long.valueOf(productId));
////            R<Object> collectProductExpandObject = remoteCollectProductService.getCollectProductExpandInfo(collectProductExpandSel);
////            String collectProductExpandJSONString = JSONObject.toJSONString(collectProductExpandObject.getData());
////            ErpCollectProductExpand collectProductExpand = JSONObject.parseObject(collectProductExpandJSONString, ErpCollectProductExpand.class);
////
////            if (collectProductExpand.getProductStatus() == 0) {
////                return R.fail("商品已下架");
////            }
//
//            R<Object> objectR1 = remoteCollectProductService.publishAutoInnerAuth(productId,userId.toString(),taskId.toString());
//
//            R<Object> collectProductPublishTaskObject = remoteCollectProductService.getCollectProductPublishTaskOneOrderByCreateTime(productId, userId);
//            String collectProductPublishTaskJSONString = JSONObject.toJSONString(collectProductPublishTaskObject.getData());
//            ErpCollectProductPublishTask publishTask = JSONObject.parseObject(collectProductPublishTaskJSONString, ErpCollectProductPublishTask.class);
//
//
//
//            if (ObjectUtils.isEmpty(publishTask)) {
//                return R.fail("从公共库商品刊登到个人库异常");
//            } else if (publishTask.getStatus() == 3 && !publishTask.getRemark().equals("该产品您已刊登，不能重复刊登！")) {
//                return R.fail(publishTask.getRemark());
//            }
//
//        }
//
//        return R.ok();
//    }

    @Override
    public R<Object> publishAeProduct(ErpAutoPulishProductProject project) {
        /** TODO 在线商品库更新上架任务ID start **/
//        Long taskId = project.getTaskId();
//        ErpSellerStoreProductExpand sellerStoreProductExpand = new ErpSellerStoreProductExpand();
//        sellerStoreProductExpand.setAutoTaskId(taskId);
//        R<Object> sellerStoreProductExpandObject = remoteSellerStoreProductService.getErpSellerStoreProductExpandInfo(sellerStoreProductExpand);
//        String sellerStoreProductExpandString = JSONObject.toJSONString(sellerStoreProductExpandObject.getData());
//        ErpSellerStoreProductExpand sellerStoreProductExpandSel = JSONObject.parseObject(sellerStoreProductExpandString, ErpSellerStoreProductExpand.class);
//
//        //判断是否成功
//        if (sellerStoreProductExpandSel.getStatus() == 3) {
//            //发布到在线商品库异常，返回原因
//            return R.fail(sellerStoreProductExpandSel.getRemark());
//        }

        /**  在线商品库更新上架任务ID end **/

        //调用上传方法
//        R<Object> pushObj = remoteSellerStoreProductService.pushInnerAuth(sellerStoreProductExpandSel.getSellerStoreProductId());
////        R<Object> pushObj = iErpSellerStoreProductService.push(sellerStoreProductExpandSel.getSellerStoreProductId());
//        if (pushObj.getCode() != 200) {
//            return R.fail(pushObj.getData());
//        }
//        return R.ok(sellerStoreProductExpandSel.getSellerStoreProductId());
        return null;
    }

    @Override
    @Transactional
    public R<Object> processAeProduct(Long sellerStoreProductId, ErpAutoPulishProductProject project) {
        R<Object> objectR = remoteSellerStoreProductService.getSellerStoreProductInfoById(sellerStoreProductId.toString());
        String toJSONString = JSONObject.toJSONString(objectR.getData());
        ErpSellerStoreProduct sellerStoreProduct = JSONObject.parseObject(toJSONString, ErpSellerStoreProduct.class);


        //异步 添加联盟折扣
        setCommission(project, sellerStoreProduct);
        //异步确认
        remoteSellerStoreProductService.confirmUploadSuccess(sellerStoreProductId);

        HashMap<String, Object> map = new HashMap<>();
        map.put("autoTaskId", project.getTaskId());
        map.put("collectProductId", sellerStoreProduct.getCollectProductId());
        map.put("sellerProductId", sellerStoreProduct.getSellerProductId());
        map.put("aeProductId", sellerStoreProduct.getAeProductId());
        map.put("remark", "上架成功");
        return R.ok(map);
    }

    @Override
    public R<Object> queryProjectById(String projectId) {
        ErpAutoPulishProductProject project = baseMapper.selectById(projectId);
        if (Objects.isNull(project)) {
            return R.fail("计划不存在");
        } else {
            return R.ok(project);
        }
    }

    @Override
    public R<Object> editPulishProject(ErpAutoPulishProductProject project) {
        project.setUpdateTime(new Date());
        if (baseMapper.updateById(project) > 0) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }

    @Override
    public R<Object> addPulishProductProject(ErpAutoPublishProductProjectBo projectBo) {

        //判断分钟数和每日上架数量对比，是否能达到一分钟一个，超出则返回异常
        // 将字符串转换为LocalTime对象
        LocalTime start = LocalTime.parse(projectBo.getPulishBeginTime());
        LocalTime end = LocalTime.parse(projectBo.getPulishEndTime());

        // 计算时间差（以分钟为单位）
        long minutesDifference = ChronoUnit.MINUTES.between(start, end);
        BigDecimal pulishNumberByDay = new BigDecimal(projectBo.getPulishNumberByDay());
        BigDecimal minutesDifferenceBD = new BigDecimal(minutesDifference);
        BigDecimal result = minutesDifferenceBD.subtract(pulishNumberByDay);
        if (result.compareTo(BigDecimal.ZERO) < 0) {
            return R.fail("目标上架时间差为" + minutesDifference + "分钟，频率太高，请减少上架数量或延长上架时间");
        }

        //设置计划状态为启用中
        projectBo.setStatus(1);

        ErpAutoPulishProductProject project = new ErpAutoPulishProductProject();
        BeanUtils.copyProperties(projectBo, project);
        project.setCreateTime(new Date());
        project.setUpdateTime(new Date());

        if (baseMapper.insert(project) > 0) {
            return R.ok("创建计划成功");
        } else {
            return R.fail("创建计划失败");
        }
    }

    @Override
    public R<Object> editPulishProjectStatus(String projectId, Integer status) {
        ErpAutoPulishProductProject project = baseMapper.selectById(projectId);
        project.setUpdateTime(new Date());
        if (Objects.isNull(project)) {
            return R.fail("计划不存在");
        } else {
            project.setStatus(status);
            if (baseMapper.updateById(project) > 0) {
                return R.ok("修改状态成功");
            } else {
                return R.fail("修改状态失败");
            }
        }
    }

    @Override
    public List<ErpAutoPulishProductProjectTask> getPulishProductProjectTaskList(Long aeProductId, String projectId, String status, String startTime, String endTime) {
        LambdaQueryWrapper<ErpAutoPulishProductProjectTask> lqw = Wrappers.lambdaQuery();
        lqw.eq(ErpAutoPulishProductProjectTask::getProjectId, projectId);
        lqw.like(aeProductId != null, ErpAutoPulishProductProjectTask::getAeProductId, aeProductId);
        lqw.eq(ErpAutoPulishProductProjectTask::getStatus, 2);
        lqw.ge(startTime != null && startTime != "", ErpAutoPulishProductProjectTask::getExecutionTime, startTime);
        lqw.le(endTime != null && endTime != "", ErpAutoPulishProductProjectTask::getExecutionTime, endTime);
        List<ErpAutoPulishProductProjectTask> productProjectList = erpAutoPulishProductProjectTaskMapper.selectList(lqw);
        return productProjectList;

    }

    @Async
    public void setCommission(ErpAutoPulishProductProject project, ErpSellerStoreProduct sellerStoreProduct) {
        sleep(5000);
        String remark = null;
        BigDecimal afflicateDiscount = null;
        if (project.getIsAfflicateDiscount() == 1) {
            afflicateDiscount = new BigDecimal(project.getAfflicateDiscount());
        } else {
            R<Object> objectR = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(project.getTemplateId()));
            String toJSONString = JSONObject.toJSONString(objectR.getData());
            ErpSellerStorePriceTemplate template = JSONObject.parseObject(toJSONString, ErpSellerStorePriceTemplate.class);
            afflicateDiscount = template.getUnion();
        }
        if (afflicateDiscount.compareTo(BigDecimal.ZERO) > 0) {
            //调用孙哥方法 TODO 暂不调用
//            R<Object> commissionObjectR = erpPythonMethodCallService.setCommission(project.getStoreId(), sellerStoreProduct.getAeProductId(), afflicateDiscount.intValue());
//            if (commissionObjectR.getCode() != 200) {
//                remark = commissionObjectR.getMsg();
//            } else {
//                remark = "联盟折扣设置成功";
//            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("taskId", project.getTaskId());
        map.put("remark", remark);
        //TODO 暂不调用
//        restTemplate.postForEntity(autoConfig.getEndpoint() + "/pulishProduct/autoPulishProductProjectTask/setCommission", map, String.class);

    }

    /**
     * 重启失败执行计划
     *
     * @return
     */
    @Override
    public R<Object> restartPulishProductProjectJob(ErpAutoPulishProductProject project, Integer count, Integer type) {
        if (project == null) {
            //1、获取昨天不为2的任务所对应的计划，并获取数量
            List<RestartProjectDto> projects = erpAutoPulishProductProjectTaskMapper.getRestartProjectList();
            for (RestartProjectDto dto : projects) {
                ErpAutoPulishProductProject project1 = baseMapper.selectById(dto.getProjectId());
                //2、复制任务，并调整执行时间
                createTaskInfo(project1, dto.getNumber(), 1);
            }
        } else {
            //执行下架计划
            createTaskInfoByUnshelf(project, count, type);
        }
        return R.ok();
    }

    @Override
    public R<Object> runlishProductProjectJobByUnshelf(Long projectId, Integer count, Integer type) {
        //执行下架计划
        ErpAutoPulishProductProject project = baseMapper.selectById(projectId);
        createTaskInfoByUnshelf(project, count, type);
        return R.ok();
    }


    @Override
    public R<Object> runProjectByStoreUserName(String storeUserName) {
        //同步授权
        System.out.println("---------1----------同步授权token开始----------");
        synchronizationToken(storeUserName);
        synchronizationToken(storeUserName);
        System.out.println("---------1----------同步授权token完成----------");
        //同步运费模版
        System.out.println("---------2----------同步运费模版开始----------");
        remoteSellerStoreFreightTemplateService.getFreightTemplateByStoreUserName(storeUserName);
        System.out.println("---------2----------同步运费模版完成----------");

//        //将所有为1的计划的根据定价模版 创建单品折扣和分组
        System.out.println("---------4----------创建活动开始----------");
        processingProjectGroupAndDiscount();
        System.out.println("---------4----------创建活动完成----------");

        System.out.println("---------5----------开始创建计划----------");
        //将计划的今日上架数量改为上限
        List<ErpAutoPulishProductProject> list = baseMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                        .eq(ErpAutoPulishProductProject::getStoreUserName, storeUserName)
                        .eq(ErpAutoPulishProductProject::getStatus, 1)
        );
        for (ErpAutoPulishProductProject project : list) {
            if (Objects.isNull(project.getProductDiscountId())) {
                project.setRemark("活动创建异常");
            } else {
                //今日上架数量改为上限
                project.setPulishNumberByDay(project.getPulishUpperLimit());
                //开始创建
                createTaskInfo(project, project.getPulishUpperLimit(), 0);
                project.setRemark("一次性执行");
            }
            project.setStatus(3);
            baseMapper.updateById(project);
        }
        System.out.println("---------5----------创建计划完成----------");

        return R.ok("执行完成");
    }

    @Override
    public R<Object> changeBindingProdjectPriceTemplate(Long projectId) {
        //找到该定价模版
        R<Object> objectR = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(projectId);
        String toJSONString = JSONObject.toJSONString(objectR.getData());
        ErpSellerStorePriceTemplate template = JSONObject.parseObject(toJSONString, ErpSellerStorePriceTemplate.class);        //找到该定价模版的对应店铺的所有计划

        //找到该用户下所有绑定的店铺
        List<ErpAutoSellerStoreConfig> storeList = erpAutoSellerStoreConfigMapper.selectList(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfig>().eq(ErpAutoSellerStoreConfig::getUserId,  template.getSellerId())
        );
        if (storeList.size() == 0) {
            return R.fail("没有绑定店铺");
        }
        for (ErpAutoSellerStoreConfig store : storeList) {
            //将计划的定价模版改成改projectId
            List<ErpAutoPulishProductProject> projectList = baseMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                            .eq(ErpAutoPulishProductProject::getStoreId, store.getStoreId())
            );
            if (projectList.size() > 0) {
                for (ErpAutoPulishProductProject project : projectList) {
                    project.setTemplateId(template.getId().toString());
                    baseMapper.updateById(project);
                }
            }else {
                continue;
            }


        }


        return R.ok("执行完毕");
    }


    /**
     * 执行上架计划
     *
     * @return
     */
    @Override
    public R<Object> runPulishProductProjectJob() {
        HashMap<String, Object> map = new HashMap<>();
        //同步授权
        System.out.println("---------1----------同步授权token开始----------");
        synchronizationToken(null);
        synchronizationToken(null);
        System.out.println("---------1----------同步授权token完成----------");
        //同步运费模版
        System.out.println("---------2----------同步运费模版开始----------");
        remoteSellerStoreFreightTemplateService.getSellerStoreFreightTemplateAll();
        System.out.println("---------2----------同步运费模版完成----------");

        //处理计划状态
        System.out.println("---------3----------确认计划状态开始----------");
//        processingProjectStatus();
        System.out.println("---------3----------确认计划状态完成----------");

//        //将所有为1的计划的根据定价模版 创建单品折扣和分组
        System.out.println("---------4----------创建活动开始----------");
        processingProjectGroupAndDiscount();
        System.out.println("---------4----------创建活动完成----------");
//        //跑计划，创建任务
        System.out.println("---------5----------创建任务开始----------");
        processingProjectCreateTask();
        System.out.println("---------5----------创建任务完成----------");

        return R.ok("执行成功");
    }


    @Override
    public R<Object> synchronizationToken(String storeUserName) {
        //获取系统中的所有自动化店铺
        List<ErpAutoSellerStoreConfig> storeList = new ArrayList<>();
        if (Objects.isNull(storeUserName)) {
            //获取系统中的所有自动化店铺
            storeList = erpAutoSellerStoreConfigMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoSellerStoreConfig>().eq(ErpAutoSellerStoreConfig::getStatus, 1)
            );
        } else {
            ErpAutoSellerStoreConfig erpAutoSellerStoreConfig = erpAutoSellerStoreConfigMapper.selectOne(
                    new LambdaQueryWrapper<ErpAutoSellerStoreConfig>().eq(ErpAutoSellerStoreConfig::getStoreAlias, storeUserName)
            );
            if (Objects.isNull(erpAutoSellerStoreConfig)) {
                return R.fail("店铺不存在");
            } else {
                storeList.add(erpAutoSellerStoreConfig);
            }
        }

        int i = 0;
        System.out.println("同步店铺有" + storeList.size() + "个");
        for (ErpAutoSellerStoreConfig store : storeList) {
            //调用接口，上老库里查询redis
            String body = HttpSendUtils.getReturnGetBody("https://pbb2c.com/erp-api/gather/test/synchronizationToken/" + store.getStoreId().toString());
//            System.out.println(body);
            if (!body.contains("200")) {
//                System.out.println(i++);

                System.out.println(store.getStoreAlias() + "  -  " + store.getStoreId() + "同步失败");

                continue;
            } else {
                System.out.println(store.getStoreAlias() + "  -  " + store.getStoreId() + "同步成功");
            }
            JSONObject bodyObj = JSONObject.parseObject(body).getJSONObject("msg");
            RedisUtils.setCacheObject(ACCESS_TOKEN_KEY + store.getStoreAlias(), bodyObj.toJSONString());
            RedisUtils.setCacheObject(ACCESS_TOKEN_KEY + store.getStoreId(), bodyObj.toJSONString());
            Object storeAliasObject = RedisUtils.getCacheObject(ACCESS_TOKEN_KEY + store.getStoreAlias());
            Object storeIdObject = RedisUtils.getCacheObject(ACCESS_TOKEN_KEY + store.getStoreId());
            //判断店铺token是否还生效


            // 获取redis有无
//            String StoreAliasStr = storeAliasObject.toString();
//            String storeIdStr = storeIdObject.toString();
//            System.out.println(StoreAliasStr);
//            System.out.println(storeIdStr);
            System.out.println(i++);
            //返回信息保存redis
        }
        return R.ok();
    }

//    public R<Object> synchronizationTokenOne(String storeUserName) {
//        ErpAutoSellerStoreConfig store = erpAutoSellerStoreConfigMapper.selectOne(
//                new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
//                        .eq(ErpAutoSellerStoreConfig::getStoreAlias,storeUserName)
//        );
//        //调用接口，上老库里查询redis
//        String body = HttpSendUtils.getReturnGetBody("https://pbb2c.com/erp-api/gather/test/synchronizationToken/" + store.getStoreId().toString());
//        if (!body.contains("200")) {
//            System.out.println(store.getStoreAlias() + "  -  " + store.getStoreId() + "同步失败");
//            return R.fail("同步失败");
//        } else {
//            System.out.println(store.getStoreAlias() + "  -  " + store.getStoreId() + "同步成功");
//        }
//        JSONObject bodyObj = JSONObject.parseObject(body).getJSONObject("msg");
//        RedisUtils.setCacheObject(ACCESS_TOKEN_KEY + store.getStoreAlias(), bodyObj.toJSONString());
//        RedisUtils.setCacheObject(ACCESS_TOKEN_KEY + store.getStoreId(), bodyObj.toJSONString());
//        Object storeAliasObject = RedisUtils.getCacheObject(ACCESS_TOKEN_KEY + store.getStoreAlias());
//        Object storeIdObject = RedisUtils.getCacheObject(ACCESS_TOKEN_KEY + store.getStoreId());
//        //返回信息保存redis
//        return R.ok();
//    }


    @Override
    public R<Object> runPulishProductProjectJobById(String id) {
        ErpAutoPulishProductProject project = baseMapper.selectById(id);
        Integer pulishNumberByDay = project.getPulishNumberByDay();
        createTaskInfo(project, pulishNumberByDay, 0);
        return R.ok();
    }


    //处理计划状态
    public R<Object> processingProjectStatus() {
        //找到所有时间小于今天的计划，状态标志位结束
        List<ErpAutoPulishProductProject> projectEndList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                        .eq(ErpAutoPulishProductProject::getStatus, 1)
                        .le(ErpAutoPulishProductProject::getPulishEndDay, new Date())
        );
        for (ErpAutoPulishProductProject project : projectEndList) {
            project.setStatus(5);
            project.setRemark("已到结束时间");
            baseMapper.updateById(project);
        }


        //找到剩余的待执行的计划
        List<ErpAutoPulishProductProject> projectList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                        .eq(ErpAutoPulishProductProject::getStatus, 1)
                        .le(ErpAutoPulishProductProject::getPulishBeginDay, new Date())
        );
        //判断上架的是否已达上限
        for (ErpAutoPulishProductProject project : projectList) {
            //看成功发布的数量
            List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .eq(ErpAutoPulishProductProjectTask::getProjectId, project.getId())
                            .in(ErpAutoPulishProductProjectTask::getStatus, 2, 12)
            );
            if (project.getPulishUpperLimit() - taskList.size() <= 0) {
                //已经达到上限
                project.setStatus(2);
                project.setRemark("已经达到上架上限（" + project.getPulishUpperLimit() + "）");
            }

            //查看类目中的剩余目标数是否大于0
            AutoQueryInfoDto dto = new AutoQueryInfoDto();
            dto.setProductTemplateType(project.getProductTemplateType());
            dto.setProductCategory(project.getProductCategory());
            dto.setPriceFloor(project.getPriceFloor());
            dto.setPriceCeiling(project.getPriceCeiling());
            dto.setProductBrand(project.getProductBrand());
            dto.setProductWarehouse(project.getProductWarehouse());
            dto.setStoreId(project.getStoreId());

            String body = queryStoreProductNumberNew(project, dto);
            Integer productNumber = Integer.valueOf(body);
            dto.setStoreId(project.getStoreId());
            if (StringUtils.isEmpty(body)) {
                project.setStatus(2);
                project.setRemark("该分类已经没有可以上架的商品");
                baseMapper.updateById(project);
                return null;
            }

            if (ObjectUtils.isNull(productNumber)) {
                project.setStatus(2);
                project.setRemark("数据返回异常");
            } else if (productNumber == 0) {
                project.setStatus(2);
                project.setRemark("该分类（" + project.getProductCategory() + "）中，已经没有可上架商品");
            }

            baseMapper.updateById(project);
        }
        return R.ok();
    }


    public String queryStoreProductNumberNew(ErpAutoPulishProductProject project, AutoQueryInfoDto dto) {
        project = handleProject(project);
        dto.setTaskProductIds(project.getTaskProductIds());
        dto.setErrorCategoryIds(project.getErrorCategoryIds());
        R<Object> objectR = remotePublishProductService.queryStoreProductNumberNew(dto);
        String body = objectR.getData().toString();
        return body;

    }

    //将所有为1的计划的根据定价模版 创建单品折扣和分组
    @Override
    public R<Object> processingProjectGroupAndDiscount() {

        //先同步一遍token
        synchronizationToken(null);

        //找到正在执行的，且分组id和活动id有一项为空的
        List<ErpAutoPulishProductProject> projectList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                        .eq(ErpAutoPulishProductProject::getStatus, 1)
                        .isNull(ErpAutoPulishProductProject::getProductDiscountId)
        );
        for (ErpAutoPulishProductProject project : projectList) {
            //需要信息
            //是否默认折扣 是否默认分组 自定义活动名称 自定义分组名称 活动id 分组id 智能定价id 店铺id
            AutoQueryPriceTemplateInfoDto templateInfo = new AutoQueryPriceTemplateInfoDto();
            templateInfo.setTemplateId(project.getTemplateId());
            templateInfo.setProductDiscount(project.getProductDiscount());
            templateInfo.setIsProductDiscount(project.getIsProductDiscount());
            templateInfo.setProductDiscountId(project.getProductDiscountId());
            templateInfo.setProductGroup(project.getProductGroup());
            templateInfo.setIsProductGroup(project.getIsProductGroup());
            templateInfo.setProductGroupId(project.getProductGroupId());
            templateInfo.setStoreId(project.getStoreId());
            templateInfo.setProductCategory(project.getProductCategory());

            //根据智能定价模版获取信息
            //TODO 改造为内部类调用
            R<Object> objectR = remoteSellerStoreActivityService.processingProjectGroupAndDiscount(templateInfo);
            if (objectR.getCode() != 200) {
                project.setStatus(3);
                project.setRemark(objectR.getMsg());
                baseMapper.updateById(project);
                continue;
            }
            String body = JSONObject.toJSONString(objectR.getData());
            System.out.println(body);
            JSONObject templateInfoRe = JSONObject.parseObject(body);
            Integer code = objectR.getCode();
            if (code == 500) {
                project.setStatus(2);
                project.setRemark(objectR.getMsg());
            } else {
//                JSONObject templateInfoRe = jsonObject.getJSONObject("data");
                //获取返回的信息
                project.setProductDiscountId(templateInfoRe.getLong("productDiscountId"));
                project.setProductDiscount(templateInfoRe.getString("productDiscount"));
//                project.setProductGroupId(templateInfoRe.getLong("productGroupId"));
            }
            baseMapper.updateById(project);
        }
        return R.ok();
    }

    @Override
    public String queryStoreProductNumberByInfo(AutoQueryInfoDto dto) {
        List<ErpAutoPulishProductProjectTask> productProjectTasks = erpAutoPulishProductProjectTaskMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                        .eq(ErpAutoPulishProductProjectTask::getStoreId, dto.getStoreId())
                        .ne(ErpAutoPulishProductProjectTask::getStatus, 2)
                        .groupBy(ErpAutoPulishProductProjectTask::getCollectProductId)
        );
        //获取任务id
        List<Long> taskProductIds = productProjectTasks.stream()
                .map(ErpAutoPulishProductProjectTask::getCollectProductId)
                .collect(Collectors.toList());

        //转为List<String>
        List<String> taskProductStrIds = taskProductIds.stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
        // 转为字符串
        dto.setTaskProductIds(String.join(",", taskProductStrIds));

        //获取异常类目
        List<ErpAutoSellerStoreConfigErrorCategory> categoryList = erpAutoSellerStoreConfigErrorCategoryMapper.selectList(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfigErrorCategory>()
                        .eq(ErpAutoSellerStoreConfigErrorCategory::getStoreId, dto.getStoreId())
        );
        //获取任务id
        List<Long> categoryIdLists = categoryList.stream()
                .map(ErpAutoSellerStoreConfigErrorCategory::getCategoryId)
                .collect(Collectors.toList());

        //转为List<String>
        List<String> categoryIdStrLists = categoryIdLists.stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
        // 转为字符串
        dto.setErrorCategoryIds(String.join(",", categoryIdStrLists));


        R<Object> objectR = remotePublishProductService.queryStoreProductNumberNew(dto);
        String body = JSONObject.toJSONString(objectR.getData());
        return body;
    }

    /**
     * 将未创建任务的计划重新执行一遍
     *
     * @return
     */
    @Override
    public R<Object> runNotCreatePulishProductProjectJob() {
        List<ErpAutoPulishProductProject> productProjectList = baseMapper.selectNotCreateProject();
        System.out.println("共有" + productProjectList.size() + "个计划未创建任务");
        int i = 1;
        for (ErpAutoPulishProductProject project : productProjectList) {
            int num = productProjectList.size() - i;
            System.out.println("计划" + project.getId() + "开始创建");
            Integer pulishNumberByDay = project.getPulishNumberByDay();
            createTaskInfo(project, pulishNumberByDay, 0);
            i++;
            System.out.println("计划" + project.getId() + "创建结束，剩余" + num + "个待创建");
        }

        return R.ok("创建完成");
    }


    /**
     * 处理计划 创建任务
     */
    private void processingProjectCreateTask() {
        List<ErpAutoPulishProductProject> projectList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                        .eq(ErpAutoPulishProductProject::getStatus, 1)
                        .lt(ErpAutoPulishProductProject::getPulishBeginDay, new Date())
        );
        int i = 0;
        for (ErpAutoPulishProductProject project : projectList) {
            Integer pulishNumberByDay = project.getPulishNumberByDay();
            createTaskInfo(project, pulishNumberByDay, 0);
            int j = projectList.size() - i;
            i++;
            System.out.println("------------5." + i + "------" + project.getId() + "创建任务完成,还剩" + j + "个计划待执行");
        }

    }

    public ErpAutoPulishProductProject handleProject(ErpAutoPulishProductProject project) {
        //找到所有上传未成功的或正在发布的
        List<ErpAutoPulishProductProjectTask> productProjectTasks = erpAutoPulishProductProjectTaskMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                        .eq(ErpAutoPulishProductProjectTask::getStoreId, project.getStoreId())
                        .ne(ErpAutoPulishProductProjectTask::getStatus, 2)
                        .groupBy(ErpAutoPulishProductProjectTask::getCollectProductId)
        );
        //获取任务id
        List<Long> taskProductIds = productProjectTasks.stream()
                .map(ErpAutoPulishProductProjectTask::getCollectProductId)
                .collect(Collectors.toList());

        //转为List<String>
        List<String> taskProductStrIds = taskProductIds.stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
        // 转为字符串
        project.setTaskProductIds(String.join(",", taskProductStrIds));

        //获取异常类目
        List<ErpAutoSellerStoreConfigErrorCategory> categoryList = erpAutoSellerStoreConfigErrorCategoryMapper.selectList(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfigErrorCategory>()
                        .eq(ErpAutoSellerStoreConfigErrorCategory::getStoreId, project.getStoreId())
        );
        //获取任务id
        List<Long> categoryIdLists = categoryList.stream()
                .map(ErpAutoSellerStoreConfigErrorCategory::getCategoryId)
                .collect(Collectors.toList());

        //转为List<String>
        List<String> categoryIdStrLists = categoryIdLists.stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
        // 转为字符串
        project.setErrorCategoryIds(String.join(",", categoryIdStrLists));

        return project;
    }

    /**
     * 正常创建任务 type = 0
     * 失败计划重建 type = 1
     * 下架重建 type = 2
     * 重复重建 type = 3
     * 重复重建后，失败再重建 type = 4
     */
    public List<Long> createTaskInfo(ErpAutoPulishProductProject project, Integer limitCount, Integer type) {
        //定时间，分钟数除以上架数量，得出间隔

        //获取开始时间
        String pulishBeginTime = project.getPulishBeginTime();
        //获取结束时间
        String pulishEndTime = project.getPulishEndTime();

        // 获取今天的日期
        String todayStr = LocalDate.now().toString();
        // 获取明天的日期
//        String todayStr = LocalDate.now().plusDays(-1).toString();

        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // 将日期字符串和时间字符串组合成日期时间对象
        // 明日开始时间
        LocalDateTime dateTime = LocalDateTime.parse(todayStr + " " + pulishBeginTime, formatter);

        // 计算间隔
        LocalTime startTime = LocalTime.parse(pulishBeginTime);
        LocalTime endTime = LocalTime.parse(pulishEndTime);

        long totalMinutes = ChronoUnit.MINUTES.between(startTime, endTime);
        BigDecimal totalMinutesBD = BigDecimal.valueOf(totalMinutes);
        BigDecimal pulishNumberByDayBD = BigDecimal.valueOf(limitCount);
        BigDecimal divide = totalMinutesBD.divide(pulishNumberByDayBD, 0, RoundingMode.DOWN);

        //筛出这个店铺上过的品
        project = handleProject(project);
//
//        List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
//                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
//                        .eq(ErpAutoPulishProductProjectTask::getStoreId, project.getStoreId())
//                        .in(ErpAutoPulishProductProjectTask::getStatus,2,3)
//
//        );
//        List<Long> taskProductIdList = taskList.stream().map(ErpAutoPulishProductProjectTask::getId)
//                .collect(Collectors.toList());
//        List<String> taskProductIdStrList = taskProductIdList.stream()
//                .map(String::valueOf)
//                .collect(Collectors.toList());
//        String taskProductIds = String.join(",", taskProductIdStrList);
//        project.setTaskProductIds(taskProductIds);

        //查找符合条件的商品
        AutoQueryInfoDto dto = BeanUtil.copyProperties(project, AutoQueryInfoDto.class);
        dto.setPulishNumberByDay(limitCount);
        R<Object> objectR = remotePublishProductService.queryAutoStoreProductListNew(dto);
        if (objectR.getCode() != 200) {
            project.setStatus(2);
            project.setRemark("该分类已经没有可以上架的商品");
            baseMapper.updateById(project);
            return null;
        }
        String body = objectR.getData().toString();
        System.out.println(body);
        JSONArray jsonArray = JSONArray.parseArray(body);
//        JSONArray jsonArray = JSONArray.parseArray(bodyJson.getString("data"));
//        System.out.println(jsonArray);


        ErpAutoPulishProductProjectTask task = new ErpAutoPulishProductProjectTask();
        task.setStoreId(project.getStoreId());
        task.setUserId(project.getUserId());
        task.setStatus(0);
        task.setAddTime(new Date());
        task.setProjectId(project.getId());
        task.setProductType(0);
        task.setRestartTaskId(Long.valueOf(type));
        BigDecimal count = BigDecimal.ZERO;

        List<Long> taskIds = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            task.setId(null);
            Long productId = (Long) jsonArray.get(i);
            //只有执行时间和id有关
            //公共库
            task.setCollectProductId(productId);
            //执行时间
            Long minutes = divide.multiply(count).longValue();
            LocalDateTime localDateTime = dateTime.plusMinutes(minutes);
//                LocalDateTime originalDateTime = LocalDateTime.parse(localDateTime.toString(), formatter);
            task.setExecutionTime(localDateTime.toString());
            count = count.add(BigDecimal.ONE);
            erpAutoPulishProductProjectTaskMapper.insert(task);
            taskIds.add(task.getId());
        }
        return taskIds;

    }

    /**
     * 创建下架任务
     */
    public R<Object> createTaskInfoByUnshelf(ErpAutoPulishProductProject project, Integer limitCount, Integer type) {
        //定时间，分钟数除以上架数量，得出间隔

        //获取开始时间
        String pulishBeginTime = project.getPulishBeginTime();
        //获取结束时间
        String pulishEndTime = project.getPulishEndTime();

        // 获取今天的日期
        String todayStr = LocalDate.now().toString();
        // 获取明天的日期
//        String todayStr = LocalDate.now().plusDays(-1).toString();

        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // 将日期字符串和时间字符串组合成日期时间对象
        // 明日开始时间
        LocalDateTime dateTime = LocalDateTime.parse(todayStr + " " + pulishBeginTime, formatter);

        // 计算间隔
        LocalTime startTime = LocalTime.parse(pulishBeginTime);
        LocalTime endTime = LocalTime.parse(pulishEndTime);

        long totalMinutes = ChronoUnit.MINUTES.between(startTime, endTime);
        BigDecimal totalMinutesBD = BigDecimal.valueOf(totalMinutes);
        BigDecimal pulishNumberByDayBD = BigDecimal.valueOf(limitCount);
        BigDecimal divide = totalMinutesBD.divide(pulishNumberByDayBD, 0, RoundingMode.DOWN);

        //筛出这个店铺上过的品
        project = handleProject(project);
//
//        List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
//                new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
//                        .eq(ErpAutoPulishProductProjectTask::getStoreId, project.getStoreId())
//                        .in(ErpAutoPulishProductProjectTask::getStatus,2,3)
//
//        );
//        List<Long> taskProductIdList = taskList.stream().map(ErpAutoPulishProductProjectTask::getId)
//                .collect(Collectors.toList());
//        List<String> taskProductIdStrList = taskProductIdList.stream()
//                .map(String::valueOf)
//                .collect(Collectors.toList());
//        String taskProductIds = String.join(",", taskProductIdStrList);
//        project.setTaskProductIds(taskProductIds);

        //查找符合条件的商品
        AutoQueryInfoDto dto = BeanUtil.copyProperties(project, AutoQueryInfoDto.class);
        dto.setPulishNumberByDay(limitCount);
        //用1688的品
//        R<Object> objectR = remotePublishProductService.queryAutoStoreProductListByUnshelf(dto);
        //用2.0的品
        R<Object> objectR = remotePublishProductService.queryAutoStoreProductListNew(dto);
        String body = objectR.getData().toString();
        System.out.println(body);
        if (objectR.getCode() != 200) {
//            project.setStatus(2);
//            project.setRemark("该分类已经没有可以上架的商品");
//            baseMapper.updateById(project);
            return R.fail("该分类已经没有可以上架的商品");
        }
        JSONArray jsonArray = JSONArray.parseArray(body);
//        JSONArray jsonArray = JSONArray.parseArray(bodyJson.getString("data"));
//        System.out.println(jsonArray);


        ErpAutoPulishProductProjectTask task = new ErpAutoPulishProductProjectTask();
        task.setStoreId(project.getStoreId());
        task.setUserId(project.getUserId());
        task.setStatus(0);
        task.setAddTime(new Date());
        task.setProjectId(project.getId());
        //用1688的品
//        task.setProductType(1);
        //用2.0的品
        task.setProductType(0);
        task.setRestartTaskId(Long.valueOf(type));
        BigDecimal count = BigDecimal.ZERO;

        List<Long> taskIds = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            task.setId(null);
            Long productId = (Long) jsonArray.get(i);
            //只有执行时间和id有关
            //公共库
            task.setCollectProductId(productId);
            //执行时间
            Long minutes = divide.multiply(count).longValue();
            LocalDateTime localDateTime = dateTime.plusMinutes(minutes);
//                LocalDateTime originalDateTime = LocalDateTime.parse(localDateTime.toString(), formatter);
            task.setExecutionTime(localDateTime.toString());
            count = count.add(BigDecimal.ONE);
            erpAutoPulishProductProjectTaskMapper.insert(task);
            taskIds.add(task.getId());
        }
        return R.ok("设置成功");

    }


    /**
     * 对于重复上架的品，下架后重新创建任务
     */
    @Override
    public R<Object> unshelfErrorAndCreateTask() {
        //1 找到现在还正常的店铺
        List<ErpAutoSellerStoreConfig> storeList = erpAutoSellerStoreConfigMapper.selectList(
                new LambdaQueryWrapper<ErpAutoSellerStoreConfig>()
                        .eq(ErpAutoSellerStoreConfig::getStatus, 1)
        );
        //循环店铺
        for (ErpAutoSellerStoreConfig store : storeList) {
            //2 找到这些店铺中的计划
            List<ErpAutoPulishProductProject> projectList = baseMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                            .eq(ErpAutoPulishProductProject::getStoreUserName, store.getStoreAlias())
            );
            //循环计划
            for (ErpAutoPulishProductProject project : projectList) {
                //3 将这些计划中为500的给找出来
                List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                        new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                                .eq(ErpAutoPulishProductProjectTask::getProjectId, project.getId())
                                .eq(ErpAutoPulishProductProjectTask::getStatus, 500)
                );

                if (taskList.size() == 0) {
                    continue;
                }
                //循环任务
                for (ErpAutoPulishProductProjectTask task : taskList) {
                    if (ObjectUtils.isNull(task.getAeProductId())) {
                        continue;
                    }
                    //4 全部下架，记录数量
                    R<Object> objectR = remoteAeProductService.productOffline(task.getAeProductId(), task.getStoreId());
                    if (objectR.getCode() == 200) {
                        task.setStatus(501);
                    } else {
                        task.setStatus(502);
                    }
                    erpAutoPulishProductProjectTaskMapper.updateById(task);
                }
                //下架的数量
                Integer number = taskList.size();

                //5 重建任务 type = 2
                createTaskInfo(project, number, 3);
            }

        }

        return R.ok();
    }

    /**
     * 对于重复上架的品，下架后重新创建任务 新版
     */
    @Override
    public R<Object> unshelfErrorAndCreateTaskNew() {
        List<String> projectList = erpAutoPulishProductProjectTaskMapper.unshelfErrorAndCreateTaskNew();
        //循环计划
        for (String projectId : projectList) {
            ErpAutoPulishProductProject project = baseMapper.selectById(projectId);

            //3 将这些计划中为500的给找出来
            List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .eq(ErpAutoPulishProductProjectTask::getProjectId, projectId)
                            .eq(ErpAutoPulishProductProjectTask::getStatus, 500)
            );

            if (taskList.size() == 0) {
                continue;
            }
            //循环任务
            for (ErpAutoPulishProductProjectTask task : taskList) {
                if (ObjectUtils.isNull(task.getAeProductId())) {
                    continue;
                }
                //4 全部下架，记录数量
                R<Object> objectR = remoteAeProductService.productOffline(task.getAeProductId(), task.getStoreId());
                if (objectR.getCode() == 200) {
                    task.setStatus(501);
                } else {
                    task.setStatus(502);
                }
                erpAutoPulishProductProjectTaskMapper.updateById(task);
            }
            //下架的数量
            Integer number = taskList.size();

            //5 重建任务 type = 2
            createTaskInfo(project, number, 3);
        }

        return R.ok();
    }

    /**
     * 将重复上架失败后的品再次重新创建
     *
     * @return
     */
    @Override
    public R<Object> unshelfErrorAndCreateTaskAgain() {
        List<ErpAutoPulishProductProject> productProjectList = baseMapper.unshelfErrorAndCreateTaskAgain();
        System.out.println("共有" + productProjectList.size() + "个计划未创建任务");
        int i = 1;
        for (ErpAutoPulishProductProject project : productProjectList) {
            int num = productProjectList.size() - i;
            System.out.println("计划" + project.getId() + "开始创建");
            List<ErpAutoPulishProductProjectTask> taskList = erpAutoPulishProductProjectTaskMapper.selectList(
                    new LambdaQueryWrapper<ErpAutoPulishProductProjectTask>()
                            .eq(ErpAutoPulishProductProjectTask::getStatus, 3)
                            .eq(ErpAutoPulishProductProjectTask::getRestartTaskId, 3)
                            .isNull(ErpAutoPulishProductProjectTask::getSellerProductId)
                            .eq(ErpAutoPulishProductProjectTask::getProjectId, project.getId())
            );
            if (taskList.size() == 0) {
                i++;
                continue;
            }
            createTaskInfo(project, taskList.size(), 4);
            i++;
            System.out.println("计划" + project.getId() + "创建结束，剩余" + num + "个待创建");
        }

        return R.ok("创建完成");
    }

    /**
     * 创建新的活动
     *
     * @param storeId
     * @return
     */
    @Override
    public R<Object> createNewProjectActivityByStoreId(Long storeId) {
        //1、获取当前店铺下的计划
        List<ErpAutoPulishProductProject> projectList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpAutoPulishProductProject>()
                        .eq(ErpAutoPulishProductProject::getStoreId, storeId)
        );
        //循环活动
        for (ErpAutoPulishProductProject project : projectList) {
            Long productDiscountId = project.getProductDiscountId();
            //2、获取当前计划的活动，确认是否过期
            //3-1、 如果未过期，则跳过

            //3-2、如果过期了，则调用孙哥接口，生成新的活动

        }
        //4、替换原计划中活动
        //5、将活动中的商品迁移

        return null;
    }

}
